const { validationResult } = require("express-validator");
const formatError = require("../utils/formatError");
const {
    addComment,
    listComment,
    deleteComment,
    findComment,
} = require("../model/comment");

// 新增评论
const AddComment = async (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
        return res.status(400).send({
            code: 400,
            msg: "参数错误",
            data: formatError(result.array()),
        });
    }
    try {
        const { id } = req.params;
        const { content } = req.body;
        const comment = await addComment({
            blog: id,
            content,
            author: req.session.user._id,
        });
        return res.status(200).send({
            code: 200,
            msg: "博客评论成功",
            data: {
                id: comment._id,
            },
        });
    } catch (err) {
        return res.status(500).send({
            code: 500,
            msg: "Internal Server Error",
        });
    }
};

// 博客对应的评论列表
const ListComment = async (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
        return res.status(400).send({
            code: 400,
            msg: "参数错误",
            data: formatError(result.array()),
        });
    }
    try {
        const blog = req.params.id;
        let { page = 1, size = 10 } = req.query;
        size = Math.max(1, size);
        page = Math.max(1, page);
        const list = await listComment(blog, size, page);
        return res.status(200).send({
            code: 200,
            msg: "获取评论列表成功",
            data: list,
        });
    } catch (error) {
        return res.status(500).send({
            code: 500,
            msg: "Internal Server Error",
        });
    }
};

// 删除评论
const DeleteComment = async (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
        return res.status(400).send({
            code: 400,
            msg: "参数错误",
            data: formatError(result.array()),
        });
    }
    try {
        const { id } = req.params;
        const comment = await findComment(id);
        if (!comment) {
            return res.status(404).send({
                code: 404,
                msg: "评论不存在",
            });
        }
        if (comment.author._id.toString() !== req.session.user._id) {
            return res.status(403).send({
                code: 403,
                msg: "没有权限删除评论",
            });
        }
        await deleteComment(id);
        return res.status(200).send({
            code: 200,
            msg: "删除评论成功",
            data: {
                id,
            },
        });
    } catch (error) {
        return res.status(500).send({
            code: 500,
            msg: "Internal Server Error",
        });
    }
};

module.exports = { AddComment, ListComment, DeleteComment };
